//
//  PrivateLetterViewController.m
//  LiveStar
//
//  Created by 漪珊 on 2017/4/17.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "PrivateLetterViewController.h"
#import "LSTextMsgCell.h"
#import "LSMessage.h"
#import "LSPraviteMsgModel.h"
#import "PraviteRecieveModel.h"

@interface PrivateLetterViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>{
    NSMutableArray *_MsgDataArray;
    UIView *_msgInputView;
    UITextField *_msgInputFeild;
}
@property (nonatomic, strong) UITableView *tableView;
@end

@implementation PrivateLetterViewController
- (UIView *)msgInputView {
    if (!_msgInputView) {
        //输入框
        _msgInputView = [[UIView alloc] initWithFrame:CGRectMake(0, kSCREEN_HEIGHT -kNAV_HEIGHT- 50, kSCREEN_WIDTH, 50 )];
        _msgInputView.backgroundColor = [UIColor whiteColor];
        UIView *sepline = [[UIView alloc] init];
        [_msgInputView addSubview:sepline];
        sepline.frame = CGRectMake(0, 0, kSCREEN_WIDTH, 0.5);
        sepline.backgroundColor = [UIColor cellLineColor];
        UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        sendBtn.frame = CGRectMake(self.view.width - 15 - 50, 0, 50, 50);
        [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
        [sendBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [sendBtn setTitleColor:UIColorFromRGB(0x0ACCAC) forState:UIControlStateNormal];
        [sendBtn setBackgroundColor:[UIColor clearColor]];
        [sendBtn addTarget:self action:@selector(clickSend:) forControlEvents:UIControlEventTouchUpInside];
        
        _msgInputFeild = [[UITextField alloc] initWithFrame:CGRectMake(10,7.5,sendBtn.left - 20,30)];
        _msgInputFeild.backgroundColor = [UIColor clearColor];
        _msgInputFeild.returnKeyType = UIReturnKeySend;
        _msgInputFeild.borderStyle = UITextBorderStyleRoundedRect;
        _msgInputFeild.placeholder = @"留下你想说的";
        _msgInputFeild.delegate = self;
        _msgInputFeild.textColor = [UIColor blackColor];
        _msgInputFeild.font = [UIFont systemFontOfSize:14];
        
        [_msgInputView addSubview:_msgInputFeild];
        [_msgInputView addSubview:sendBtn];
        
    }
    
    
    //    [_msgInputFeild becomeFirstResponder];
    return _msgInputView;
}

#pragma mark -- 私信历史记录
- (void)pravitelistRequest {
    NSDictionary *dict =  @{@"udid":User_ID,
                            @"token":TOKEN,
                            @"suid":self.suid,
                            @"page":@"1",
                            };
    NSString *urlString = [TEST_URL stringByAppendingString:kPraviteHistory];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            NSArray *array = responseObject[@"data"][@"list"];
            for (NSDictionary *praviteDict in array) {
                LSPraviteMsgModel *model = [[LSPraviteMsgModel alloc] initWithDict:praviteDict];
                LSMessage *message = [[LSMessage alloc] init];
                message.praviteModel = model;
                message.text = model.c_content;
                message.messageType = LSMessageTypeText;
                if ([model.c_udid intValue] == [User_ID intValue]) { //发送消息人
                    message.msgOwnerType = LSMsgOwnerTypeSelf;
                } else {
                    message.msgOwnerType = LSMsgOwnerTypeOther;
                }
                [_MsgDataArray addObject:message];
            }
            [self.tableView reloadData];
        }
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];}
#pragma mark -- 发送私信
- (void)sendPresentRequestWithMessage:(NSString *)message {
    NSDictionary *dict = @{@"udid":User_ID,
                           @"token":TOKEN,
                           @"cid":self.suid,
                           @"type":@"40",
                           @"description":message,
                           @"parent":User_ID,//粉丝id
                           @"pudid":self.suid //接收者id
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kSendComment];
    [self showHUDInView:self.view title:@"发送中"];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        [self hideHUD];
        if ([responseObject[@"code"] intValue] == 200) {
            _msgInputFeild.text = nil;
            _msgInputFeild.placeholder = @"请输入文字...";
            [self showTitle:responseObject[@"data"][@"message"]];
            NSDictionary *newData = responseObject[@"data"][@"comment"];
            [self uploadPraviteListWithData:newData];
        }
    } failureBlock:^(NSError *error) {
        [self hideHUD];
    } showHUD:NO];
}

- (void)uploadPraviteListWithData:(NSDictionary *)newData {
    LSPraviteMsgModel *model = [[LSPraviteMsgModel alloc] init];
    model.c_udid = newData[@"c_udid"];
    model.c_content = newData[@"c_content"];
    model.pnickname = @"";
    model.c_parudid = newData[@"c_parudid"];
    model.pavatar = newData[@"u_avatar"];
    model.cnickname = newData[@"u_nickname"];
    model.c_createtime = newData[@"c_createtime"];
    model.ctype = @"";
    model.cavatar = newData[@"u_avatar"];
    model.c_parent = newData[@"c_parent"];
    LSMessage *message = [[LSMessage alloc] init];
    message.praviteModel = model;
    message.text = model.c_content;
    message.messageType = LSMessageTypeText;
    message.msgOwnerType = LSMsgOwnerTypeSelf;
    [_MsgDataArray insertObject:message atIndex:_MsgDataArray.count];
    NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_MsgDataArray.count-1 inSection:0];
    [indexPaths addObject: indexPath];
    [self.tableView beginUpdates];
    [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
    [self.tableView endUpdates];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpUI];
    [self pravitelistRequest];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameDidChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    self.navigationItem.title = @"私信";
    
}

- (void)setUpUI {
    _MsgDataArray = [NSMutableArray arrayWithCapacity:1];
    //tableView
    [self creatTableView];
    [self.view addSubview:self.msgInputView];

}

//监听键盘高度变化
-(void)keyboardFrameDidChange:(NSNotification*)notice
{
    NSDictionary * userInfo = notice.userInfo;
    NSValue * endFrameValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect endFrame = endFrameValue.CGRectValue;
    [UIView animateWithDuration:0.25 animations:^{
        _msgInputView.y = endFrame.origin.y - _msgInputView.height - kNAV_HEIGHT;
    }];
}

- (void)creatTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_HEIGHT -kNAV_HEIGHT - 50)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.tableView registerClass:[LSTextMsgCell class] forCellReuseIdentifier:@"LSTextMsgCellID"];
    [self.view addSubview:self.tableView];
}

#pragma mark -- tableView 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _MsgDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LSMessage *message = _MsgDataArray[indexPath.row];
    id cell = [tableView dequeueReusableCellWithIdentifier:message.cellIndentify];
    [cell setMessage:message];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}

#pragma mark -- 区头视图

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    LSMessage *message = _MsgDataArray[indexPath.row];
    return message.cellHeight;
}


#pragma mark -- 发送留言
- (void)clickSend:(UIButton *)sender {
    [_msgInputFeild resignFirstResponder];
    if (_msgInputFeild.text.length) {
        [self sendPresentRequestWithMessage:_msgInputFeild.text];
    } else {
        [self showTitle:@"发送内容不能为空"];
    }
}

#pragma mark -- UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [_msgInputFeild resignFirstResponder];
    if (_msgInputFeild.text.length) {
        [self sendPresentRequestWithMessage:_msgInputFeild.text];
    } else {
        [self showTitle:@"发送内容不能为空"];
    }
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
